package com.song.exceptin;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.print.FlavorException;
import java.io.PrintWriter;

/**
 * @author TonySong
 * @date 2024/5/10 0010
 * @time 10:42
 */
@Component
@Slf4j
public class MyBlockException implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
           //设置响应内容为json
           response.setContentType("application/json;charset=utf-8");
           PrintWriter out = response.getWriter();
           String msg="";
           if(e instanceof FlowException){
               msg ="流控异常";
           }if(e instanceof DegradeException) {
            msg = "降级异常";
           }
           if(e instanceof AuthorityException){
               msg = "授权异常";
           }
           if(e instanceof SystemBlockException){
               msg = "系统异常";
           }if(e instanceof ParamFlowException) {
               msg ="热点流控！";
          }
           int status = response.getStatus();
//           out.write("{\"code\":\"500" +msg+":\"请求过于频繁\"}");
        out.print("{\"code\":\""+ status + "\",\"message\":\""+msg + "\"}");
           out.flush();
           out.close();
    }
}
